package com.itheima.gatewayadmin.filters;

import cn.hutool.core.util.StrUtil;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * @version 1.0
     * @description 网关统一鉴权
     * @package com.itheima.gatewayadmin.filters
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2. 获取请求路径
        String path = request.getURI().getPath();
        log.info("用户请求了路径：{}" , path);
        //3. 对登录请求放行
        if (path.endsWith("/login/in")){
            // 放行
            return chain.filter(exchange);
        }
        //4. 获取请求头参数
        String token = request.getHeaders().getFirst("token");
        // 如果token有值
        if (StrUtil.isNotEmpty(token)){
            // 解析token，验证token的有效性
            if (AppJwtUtil.verifyToken(token) == SystemConstants.JWT_OK){
                return chain.filter(exchange);
            }
        }
        //4.2 否则拦截，报401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
